package ps.client.gui.util.textpanel;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.util.LinkedList;

import javax.swing.JLabel;
import javax.swing.JPanel;


@SuppressWarnings("serial")
public class TextPanel extends JPanel {
	
	LinkedList<TextLine> lines = new LinkedList<TextLine>();
	
	int width = 0;
	int height = 0;
	
	public TextPanel() {
		setLayout(null);
		setBackground(Color.BLACK);
		doLayout();
	}
	
	public void appendLine(TextLine line) {
		lines.add(line);
		line.setMaximumWidth(getVisibleRect().width);
//		line.validate();
		line.setBounds(0, height, line.getPreferredSize().width, line.getPreferredSize().height);
		add(line);
		if (line.getPreferredSize().width > width) {
			width = line.getPreferredSize().width;
		}
		height += line.getPreferredSize().height;
		setPreferredSize(new Dimension(width, height));
		if (getParent() != null) {
			getParent().validate();
		}
//		validate();
		repaint();
	}
	
	public void doLayout() {
		width = 0;
		height = 0;
		int maxWidth = getVisibleRect().width - 5;
		for (int i = 0; i < lines.size(); i++) {
			TextLine line = lines.get(i);
			line.setMaximumWidth(maxWidth);
//			line.validate();
			line.setBounds(0, height, line.getPreferredSize().width, line.getPreferredSize().height);
			if (line.getPreferredSize().width > width) {
				width = line.getPreferredSize().width;
			}
			height += line.getPreferredSize().height;
		}
		setPreferredSize(new Dimension(width, height));
		super.doLayout();
	}
	
	public void appendLine(Component comp) {
		TextLine line = new TextLine(new LinePart(comp));
		line.setBackground(Color.BLACK);
		appendLine(line);
	}
	
	public void appendLine(String str) {
		JLabel label = new JLabel(str);
		label.setForeground(Color.WHITE);
		appendLine(label);
	}
	
	public void appendLine(String str, Color fg) {
		JLabel label = new JLabel(str);
		label.setForeground(fg);
		appendLine(label);
	}
	
	public void clearText() {
	    lines.clear();
	    removeAll();
	    doLayout();
	    
        if (getParent() != null) {
            getParent().validate();
        }
        repaint();
	}

}
